package com.xjh.mange.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjh.mange.common.constant.ResponseConst;
import com.xjh.mange.common.constant.UserSessionName;
import com.xjh.mange.common.util.Md5Utils;
import com.xjh.mange.common.util.MyUtil;
import com.xjh.mange.model.LoginError;
import com.xjh.mange.model.User;
import com.xjh.mange.service.UserService;
import com.xjh.mange.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;

/**
 * @author 徐佳辉
 * @date 2020/8/4 18:52
 */
@Controller
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {

    /**
     * 出错次数限制（大于等于）
     */
    public static final int COUNT = 5;
    /**
     * 1秒钟的毫秒数
     */
    public static final int MS = 1000;
    /**
     * 1分钟的秒数
     */
    public static final int S = 60;
    /**
     * 分钟数设置
     */
    public static final int M = 5;
    @Autowired
    private UserService userService;


    /**
     * 登录
     * 错误 COUNT 次，等 M 分钟才能登陆
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseVO login(User user, HttpSession session) {
        if (user == null) {
            return ResponseVO.error(ResponseConst.NOT_NULL);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", user.getUserName());
        User one = userService.getOne(wrapper);
        LoginError err = (LoginError) session.getAttribute(UserSessionName.LOGIN_ERROR_COUNT);
        if (err == null) {
            LoginError loginError = new LoginError();
            loginError.setCount(0);
            session.setAttribute(UserSessionName.LOGIN_ERROR_COUNT, loginError);
            err = (LoginError) session.getAttribute(UserSessionName.LOGIN_ERROR_COUNT);
        }
        if (err.getLockTime() != null) {
            if (System.currentTimeMillis() - err.getLockTime().getTime() > MS * S * M) {
                err.setCount(0);
                session.setAttribute(UserSessionName.LOGIN_ERROR_COUNT, err);
            } else {
                return ResponseVO.error("请 " + (M - ((System.currentTimeMillis() - err.getLockTime().getTime()) / (MS * S))) + " 分钟后再试;");
            }
        }
        if (one == null) {
            err.setCount(err.getCount() + 1);
            session.setAttribute(UserSessionName.LOGIN_ERROR_COUNT, err);
            if (err.getCount() >= COUNT) {
                log.info("用户名出错 err:[{}]", err);
                err.setLockTime(new Date());
                session.setAttribute(UserSessionName.LOGIN_ERROR_COUNT, err);
                return ResponseVO.error("出错超过" + COUNT + "次，请" + M + "分钟后再试;");
            }
            return ResponseVO.error("用户名或密码错误");
        }
        if (one.getPassword().equals(Md5Utils.string2Md5(user.getPassword()))) {
            session.setAttribute(UserSessionName.USER, one);
            User byId = userService.getById(3);
            byId.setPassword(Md5Utils.string2Md5(String.valueOf(555)));
            userService.updateById(byId);
            return ResponseVO.ok("登录成功");
        } else {
            err.setCount(err.getCount() + 1);
            log.info("密码出错 err:[{}]", err);
            session.setAttribute(UserSessionName.LOGIN_ERROR_COUNT, err);
            if (err.getCount() >= COUNT) {
                err.setLockTime(new Date());
                session.setAttribute(UserSessionName.LOGIN_ERROR_COUNT, err);
                return ResponseVO.error("出错超过" + COUNT + "次，请" + M + "分钟后再试;");
            }
            return ResponseVO.error("用户名或密码错误");
        }
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @PostMapping("/logout")
    @ResponseBody
    public ResponseVO loginout(HttpSession session) {
        session.removeAttribute(UserSessionName.USER);
        return ResponseVO.ok(ResponseConst.LOGOUT);
    }

    /**
     * 获取名字
     *
     * @param session
     * @return
     */
    @GetMapping("/name")
    @ResponseBody
    public ResponseVO getNameBySession(HttpSession session) {
        User user = (User) session.getAttribute(UserSessionName.USER);
        return ResponseVO.ok(user);
    }


}
